package com.pig4cloud.pig.ads.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dy.sdk.client.DyKsClient;
import com.dy.sdk.model.request.ks.KsImageUploadRequest;
import com.dy.sdk.model.request.ks.KsVideoUploadRequest;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.ads.pig.mapper.AdMaterialPushBoxMapper;
import com.pig4cloud.pig.ads.service.AdMaterialPlatformService;
import com.pig4cloud.pig.ads.service.AdMaterialPushWorkerService;
import com.pig4cloud.pig.ads.service.AdMaterialService;
import com.pig4cloud.pig.ads.service.AdvertiserService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.AccountToken;
import com.pig4cloud.pig.api.entity.AdMaterial;
import com.pig4cloud.pig.api.entity.AdMaterialPlatform;
import com.pig4cloud.pig.api.entity.AdMaterialPushBox;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.util.Constants;
import com.pig4cloud.pig.api.util.MapUtils;
import com.pig4cloud.pig.common.core.constant.enums.MaterialTypeEnum;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.exception.CheckedException;
import com.pig4cloud.pig.common.security.util.SecurityUtils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 素材推送组件
 * @author Administrator
 *
 */
@Slf4j
@Service

public class AdMaterialPushWorker implements AdMaterialPushWorkerService{

	@Autowired
	private TtAccesstokenService ttAccesstokenService;
	
	@Autowired
	private GdtAccesstokenService gdtAccesstokenService;
	
	@Autowired
	private AdvertiserService advertiserService;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	private AdMaterialPlatformService adMaterialPlatformService;
	
	@Autowired
	private AdMaterialPushBoxMapper adMaterialPushBoxMapper;
	
	@Autowired 
	private AdMaterialService adMaterialService;
	
	/**
	 * 添加图片文件
	 */
	@Value(value = "${gdt_images_add_url}")
	private String gdtImagesAddUrl;
	
	/**
	 * 广点通上传视频接口地址前缀
	 */
	@Value(value = "${gdt_url}")
	private String gdtUrl;
	@Value(value = "${gdt_video_add}")
	private String gdtVideoAdd;
	
	/**
	 * 头条上传视频请求地址
	 */
	private String openApiUrlToutiao = "https://ad.oceanengine.com/open_api/2/file/video/ad/";

	/**
	 * 同步-推送素材
	 * @return
	 */
	@Override
	public List<AdMaterialPlatform> syncPushAdMateria(String loginUserId, List<AdMaterialPushBox> entitys){
		List<AdMaterialPlatform> result = new ArrayList<>();
		for (AdMaterialPushBox bean : entitys) {
			Long materialId = bean.getMaterialId();
			AdMaterial adMaterial = adMaterialService.getById(materialId);
			result.add(pushAdMateria(loginUserId, bean.getAdvertiserId(), bean.getPlatformId(), adMaterial));
		}
		return result;
	}
	
	/**
	 * 异步推送素材
	 * @Async 注解失效注意,不能在一个类中内部调用
	 * 故将同步和异步调用分开为2个服务
	 */
	@Async("threadPoolTaskExecutor")
	@Override
	public void asyncPushAdMateria(String loginUserId, String advertiserId, Integer platformId,
			AdMaterial adMaterial) {
		pushAdMateria(loginUserId, advertiserId, platformId, adMaterial);
	}
	
	public AdMaterialPlatform pushAdMateria(String loginUserId, String advertiserId, Integer platformId,
			AdMaterial adMaterial){
		String failMsg = "";
		Integer pushStatus = Constants.FINISH_PUSH;
		try {
			AdMaterialPlatform entity = pushPlatform(loginUserId,advertiserId, platformId.toString(), adMaterial);
			//推送成功,更新表
			adMaterialPlatformService.save(entity);
			return entity;
		} catch (CheckedException e) {
			failMsg = e.getMessage();
			pushStatus = Constants.FAIL_HPUSH;
		} catch (Exception e) {
			log.error("素材推送异常：", e);
			failMsg = "推送异常";
			pushStatus = Constants.FAIL_HPUSH;
		} finally {
			// 删除正在推送素材信息
			String key = getCachePushKey(loginUserId, advertiserId, adMaterial.getId());
			redisTemplate.delete(key);
			// 更新素材推送箱推送状态
			AdMaterialPushBox udapteBean = new AdMaterialPushBox();
			udapteBean.setAdvertiserId(advertiserId);
			udapteBean.setPlatformId(platformId);
			udapteBean.setCreateUser(loginUserId);
			udapteBean.setPushStatus(pushStatus);
			udapteBean.setFailMsg(failMsg);
			adMaterialPushBoxMapper.updatePushStatus(udapteBean);
		}
		return null;
	}
	

	/**
	 * 获取推送中缓存key
	 * @return
	 */
	private String getCachePushKey(String loginUserId, String advertiserId, Long materialId){
		return Constants.AD_MATERIAL_PROGRESS_PUSH_PRIX + loginUserId + "_" + advertiserId + "_" + materialId;
	}
	
	public AdMaterialPlatform pushPlatform(String loginUserId,String advertiserId, String platformId, AdMaterial adMaterial) {
		AdMaterialPlatform adMaterialPlatform;
		switch (Objects.requireNonNull(PlatformTypeEnum.getByValue(platformId))) {
		case TT:
			adMaterialPlatform = MaterialTypeEnum.VIDEO.getType().intValue() == adMaterial.getType()
					? this.pushVideoToutiao(loginUserId,advertiserId.toString(), adMaterial)
					: this.pushPictureToutiao(loginUserId,advertiserId.toString(), adMaterial);
			break;
		case GDT:
			adMaterialPlatform = MaterialTypeEnum.VIDEO.getType().intValue() == adMaterial.getType()
					? this.pushVideoGdt(loginUserId,advertiserId.toString(), adMaterial)
					: this.pushPictureGdt(loginUserId,advertiserId.toString(), adMaterial);
			break;
		case KS:
			adMaterialPlatform = MaterialTypeEnum.VIDEO.getType().intValue() == adMaterial.getType()
					? this.pushVideoKs(loginUserId,advertiserId.toString(), adMaterial)
					: this.pushPictureKs(loginUserId,advertiserId.toString(), adMaterial);
			break;
		default:
			throw new CheckedException("无效的平台ID");
		}
		return adMaterialPlatform;
	}
	
	/**
	 * 图片上传头条
	 * @param advertiserId 广告账户
	 * @param adMaterial   视频素材信息对象
	 * @return
	 */
	@Override
	public AdMaterialPlatform pushPictureToutiao(String loginUserId, String advertiserId, AdMaterial adMaterial) {
		//定义头条接口url
		String url = "https://ad.oceanengine.com/open_api/2/file/image/ad/";

		Map<String, Object> data = new HashMap<>();
		data.put("advertiser_id", advertiserId);
		data.put("upload_type", "UPLOAD_BY_URL");
		data.put("image_url", adMaterial.getFileUrl());
		data.put("filename", adMaterial.getName());
		//公共方法获取accessToken
		String accessToken = ttAccesstokenService.fetchAccesstoken(advertiserId);
		//调第三方平台（头条）接口
		JSONObject resultStr = this.uploadAdimage(url, data, accessToken);
		ResponseBean resBean = JSON.parseObject(resultStr.toJSONString(), ResponseBean.class);
		//调用成功
		if (resBean != null && "0".equals(resBean.getCode())) {
			Map<String, Object> resData = resBean.getData();
			AdMaterialPlatform adp = new AdMaterialPlatform();
			// 1 头条
			adp.setPlatformId(Integer.valueOf(PlatformTypeEnum.TT.getValue()));
			adp.setMaterialId(adMaterial.getId());
			// 广告账户
			adp.setAdvertiserId(advertiserId);
			adp.setPlatformFileId(String.valueOf(resData.get("id")));
			adp.setPlatformMaterialId(String.valueOf(resData.get("material_id")));
			adp.setMd5(adMaterial.getMd5());
			adp.setCreateUser(loginUserId);
			adp.setCreateTime(new Date());
			return adp;
		} else {
			throw new CheckedException("图片同步头条失败：" + resBean.getMessage());
		}
	}
	
	/**
	 * 调用头条接口上传视频
	 *
	 * @param url
	 * @param data
	 * @param token
	 * @return
	 */
	public JSONObject uploadAdimage(String url, Map<String, Object> data, String token) {
		// 构造请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Access-Token", token);
		// 文件参数
		MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
		// 其他参数
		entityBuilder.addTextBody("advertiser_id", String.valueOf(data.get("advertiser_id")));
		entityBuilder.addTextBody("image_url", String.valueOf(data.get("image_url")));
		entityBuilder.addTextBody("upload_type", String.valueOf(data.get("upload_type")));
		ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
		entityBuilder.addTextBody("filename", String.valueOf(data.get("filename")), contentType);
		HttpEntity entity = entityBuilder.build();
		CloseableHttpResponse response = null;
		CloseableHttpClient client = null;

		try {
			client = HttpClientBuilder.create().build();
			httpPost.setURI(URI.create(url));
			httpPost.setEntity(entity);
			response = client.execute(httpPost);
			if (response != null && response.getStatusLine().getStatusCode() == 200) {
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				StringBuilder result = new StringBuilder();
				String line = "";
				while ((line = bufferedReader.readLine()) != null) {
					result.append(line);
				}
				return JSONObject.parseObject(result.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 视频上传头条
	 *
	 * @param advertiserId 广告账户
	 * @param adMaterial   视频素材信息对象
	 * @return
	 */
	@Override
	public AdMaterialPlatform pushVideoToutiao(String loginUserId,String advertiserId, AdMaterial adMaterial) {
		if (Double.parseDouble(adMaterial.getDuration()) < 4) {
			throw new CheckedException("视频时长小于4秒同步失败");
		}
		//获取token
		String accessToken = ttAccesstokenService.fetchAccesstoken(advertiserId);

		Map<String, Object> params = new HashMap<>();
		params.put("advertiser_id", advertiserId);
		params.put("md5", adMaterial.getMd5());
		params.put("realPath", adMaterial.getRealPath());
		params.put("filename", adMaterial.getName());
		//调第三方平台接口
		log.info(">>>推送视频头条params：{}", JSON.toJSONString(params));
		JSONObject resultStr = this.uploadAdvideo(openApiUrlToutiao, params, accessToken);
		ResponseBean resBean = JSON.parseObject(resultStr.toJSONString(), ResponseBean.class);
		//调用成功
		if (resBean != null && "0".equals(resBean.getCode())) {
			Map<String, Object> data = resBean.getData();
			AdMaterialPlatform adp = new AdMaterialPlatform();
			// 1头条
			adp.setPlatformId(Integer.valueOf(PlatformTypeEnum.TT.getValue()));
			adp.setMaterialId(adMaterial.getId());
			// 广告账户
			adp.setAdvertiserId(advertiserId);
			adp.setPlatformFileId(String.valueOf(data.get("video_id")));
			adp.setPlatformMaterialId(String.valueOf(data.get("material_id")));
			adp.setMd5(adMaterial.getMd5());
			adp.setCreateUser(loginUserId);
			adp.setCreateTime(new Date());
			log.info(">>>平台视频ID:{}，广告账户:{}，头条视频ID:{} >>>素材ID:{}，同步成功", adMaterial.getId(), advertiserId, adp.getPlatformFileId(), adp.getPlatformMaterialId());
			return adp;
		} else {
			if (Objects.isNull(resBean)) {
				throw new CheckedException("操作失败，未知错误");
			} else {
				String msg = ">>>视频ID：" + adMaterial.getId() + "，广告账户：" + advertiserId + "，失败，原因：" + resBean.getMessage();
				log.info(msg);
				throw new CheckedException(msg);
			}
		}
	}
	
	/**
	 * 视频上传广点通
	 *
	 * @param advertiserId 广告账户
	 * @param adMaterial   视频素材信息对象
	 * @return
	 */
	@Override
	public AdMaterialPlatform pushVideoGdt(String loginUserId, String advertiserId, AdMaterial adMaterial) {
		//公共方法获取accessToken
		Map<String, String> map = gdtAccesstokenService.fetchAccesstoken(advertiserId);
		//定义广点通接口url
		String url = gdtUrl + gdtVideoAdd + "?" + MapUtils.queryString(map);
		// 文件参数
		FileBody file = new FileBody(new File(adMaterial.getRealPath()));
		MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create()
				.addPart("video_file", file);
		// 其他参数
		entityBuilder.addTextBody("account_id", advertiserId);
		entityBuilder.addTextBody("signature", adMaterial.getMd5());
		ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
		entityBuilder.addTextBody("description", adMaterial.getName(),contentType);
		//调第三方平台（广点通）接口
		String resultStr = OEHttpUtils.doFilePost(url, entityBuilder);
		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		//调用成功,信息入库
		if (resBean != null && "0".equals(resBean.getCode())) {
			Map<String, Object> data = resBean.getData();
			AdMaterialPlatform adp = new AdMaterialPlatform();
			// 2广点通
			adp.setPlatformId(Integer.valueOf(PlatformTypeEnum.GDT.getValue()));
			adp.setMaterialId(adMaterial.getId());
			// 广告账户
			adp.setAdvertiserId(advertiserId);
			adp.setPlatformFileId(String.valueOf(data.get("video_id")));
			adp.setPlatformMaterialId(String.valueOf(data.get("video_id")));
			adp.setMd5(adMaterial.getMd5());
			adp.setCreateUser(loginUserId);
			adp.setCreateTime(new Date());
			log.info(">>>平台视频ID:{}，广告账户:{}，广点通视频ID:{}，同步成功", adMaterial.getId(), advertiserId, adp.getPlatformFileId());
			return adp;
		} else {
			if (Objects.isNull(resBean)) {
				throw new CheckedException("操作失败，未知错误");
			} else {
				String msg = ">>>广点通视频ID：" + adMaterial.getId() + "，广告账户：" + advertiserId + "，失败，原因：" + resBean.getMessage();
				log.info(msg);
				throw new CheckedException(msg);
			}
		}
	}
	
	/**
	 * 调用头条接口上传视频
	 *
	 * @param url
	 * @param data
	 * @param token
	 * @return
	 */
	public JSONObject uploadAdvideo(String url, Map<String, Object> data, String token) {
		// 构造请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Access-Token", token);

		// 文件参数
		FileBody file = new FileBody(new File(String.valueOf(data.get("realPath"))));
		MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create()
				.addPart("video_file", file);
		// 其他参数
		entityBuilder.addTextBody("advertiser_id", String.valueOf(data.get("advertiser_id")));
		entityBuilder.addTextBody("video_signature", String.valueOf(data.get("md5")));
		ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
		entityBuilder.addTextBody("filename", String.valueOf(data.get("filename")), contentType);
		HttpEntity entity = entityBuilder.build();

		CloseableHttpResponse response = null;
		CloseableHttpClient client = null;

		try {
			client = HttpClientBuilder.create().build();
			httpPost.setURI(URI.create(url));
			httpPost.setEntity(entity);
			response = client.execute(httpPost);
			if (response != null && response.getStatusLine().getStatusCode() == 200) {
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				StringBuilder result = new StringBuilder();
				String line = "";
				while ((line = bufferedReader.readLine()) != null) {
					result.append(line);
				}
				return JSONObject.parseObject(result.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 视频上传快手
	 *
	 * @param advertiserId 广告账户
	 * @param adMaterial   视频素材信息对象
	 * @return
	 */
	@SneakyThrows
	@Override
	public AdMaterialPlatform pushVideoKs(String loginUserId, String advertiserId, AdMaterial adMaterial)  {
		if (!"mp4".equalsIgnoreCase(adMaterial.getFormat())) {
			throw new CheckedException("快手只支持mp4格式视频,同步失败");
		}
		//公共方法获取accessToken
		AccountToken ksAccountToken = advertiserService.getAdvertiserToken(PlatformTypeEnum.KS.getValue(),advertiserId);
		if(ksAccountToken==null){
			throw new CheckedException("账号不存在或不匹配");
		}
		DyKsClient ksClient = new DyKsClient("");
		KsVideoUploadRequest request  = new KsVideoUploadRequest();
		request.setAdvertiser_id(Long.parseLong(advertiserId));
		request.setFile(adMaterial.getRealPath());
		request.setPhoto_name(adMaterial.getName());
		request.setSignature(adMaterial.getMd5());
		Integer widt = Integer.parseInt(adMaterial.getWidth());
		Integer height = Integer.parseInt(adMaterial.getHeight());
		//1：信息流竖版视频（默认） 2：信息流横版视频
		request.setType(widt > height ? 2:1);
		String result = ksClient.call4File(request,ksAccountToken.getAccessToken());
		ResponseBean resBean = JSON.parseObject(result, ResponseBean.class);
		//调用成功,信息入库
		if (resBean != null && "0".equals(resBean.getCode())) {
			Map<String, Object> data = resBean.getData();
			AdMaterialPlatform adp = new AdMaterialPlatform();
			adp.setPlatformId(Integer.valueOf(PlatformTypeEnum.KS.getValue()));
			adp.setMaterialId(adMaterial.getId());
			// 广告账户
			adp.setAdvertiserId(advertiserId);
			adp.setPlatformFileId(String.valueOf(data.get("photo_id")));
			adp.setPlatformMaterialId(String.valueOf(data.get("photo_id")));
			adp.setMd5(adMaterial.getMd5());
			adp.setCreateUser(loginUserId);
			adp.setCreateTime(new Date());
			log.info(">>>平台视频ID:{}，广告账户:{}，快手视频ID:{}，同步成功", adMaterial.getId(), advertiserId, adp.getPlatformFileId());
			return adp;
		} else {
			if (Objects.isNull(resBean)) {
				throw new CheckedException("操作失败，未知错误");
			} else {
				String msg = ">>>快手视频ID：" + adMaterial.getId() + "，广告账户：" + advertiserId + "，失败，原因：" + resBean.getMessage();
				log.info(msg);
				throw new CheckedException(msg);
			}
		}
	}
	
	/**
	 * 图片上传快手
	 * @param advertiserId 广告账户
	 * @param adMaterial   图片信息对象
	 * @return
	 */
	@SneakyThrows
	@Override
	public AdMaterialPlatform pushPictureKs(String loginUserId, String advertiserId, AdMaterial adMaterial) {
		//公共方法获取accessToken
		AccountToken ksAccountToken = advertiserService.getAdvertiserToken(PlatformTypeEnum.KS.getValue(),advertiserId);
		if(ksAccountToken==null){
			throw new CheckedException("账号不存在或不匹配");
		}
		DyKsClient ksClient = new DyKsClient("");
		KsImageUploadRequest request  = new KsImageUploadRequest();
		request.setAdvertiser_id(Long.parseLong(advertiserId));
		request.setKsurl(adMaterial.getFileUrl());
		request.setUpload_type(2);
		Integer widt = Integer.parseInt(adMaterial.getWidth());
		Integer height = Integer.parseInt(adMaterial.getHeight());
		//5：联盟图片素材； 6：横版图片；
		request.setType(widt > height ? 6:5);
		request.setSignature(adMaterial.getMd5());
		String result = ksClient.call4Form(request,ksAccountToken.getAccessToken());
		//{"code":0,"message":"OK","data":{"url":"https://static.yximgs.com/udata/pkg/market556d954922e54fb591056153e90975ee.jpg","width":1080,"height":1920,"size":142924,"format":"jpg","signature":"e115f25cf263b27658106079c2c2b4fc","pic_type":0,"image_token":"market556d954922e54fb591056153e90975ee.jpg","pic_id":"5221079348387967721"},"request_id":"b8147eacf7274724b1801c4ee54cf24e"}
		ResponseBean resBean = JSON.parseObject(result, ResponseBean.class);
		//调用成功
		if (resBean != null && resBean.getCode() != null && "0".equals(resBean.getCode())) {
			Map<String, Object> data = resBean.getData();
			AdMaterialPlatform adp = new AdMaterialPlatform();
			// 1 广点通
			adp.setPlatformId(Integer.valueOf(PlatformTypeEnum.KS.getValue()));
			adp.setMaterialId(adMaterial.getId());
			// 广告账户
			adp.setAdvertiserId(advertiserId);
			adp.setPlatformFileId(String.valueOf(data.get("pic_id")));
			adp.setPlatformMaterialId(String.valueOf(data.get("pic_id")));
			adp.setMd5(adMaterial.getMd5());
			adp.setCreateUser(loginUserId);
			adp.setCreateTime(new Date());
			return adp;
		} else {
			throw new CheckedException("图片同步快手失败：" + resBean.getMessage());
		}
	}
	
	/**
	 * 图片上传广点通
	 *
	 * @param advertiserId 广告账户
	 * @param adMaterial   视频素材信息对象
	 * @return
	 */
	@Override
	public AdMaterialPlatform pushPictureGdt(String loginUserId, String advertiserId, AdMaterial adMaterial) {
		//公共方法获取accessToken
		Map<String, String> map = gdtAccesstokenService.fetchAccesstoken(advertiserId);
		//定义广点通接口url
		String url = gdtUrl + gdtImagesAddUrl + "?" + MapUtils.queryString(map);
		Map<String, Object> params = new HashMap<>();
		params.put("account_id", advertiserId);
		params.put("upload_type", "UPLOAD_TYPE_FILE");
		params.put("signature", adMaterial.getMd5());
		params.put("realPath", adMaterial.getRealPath());
		params.put("description", adMaterial.getName());
		//调第三方平台（头条）接口
		JSONObject resultStr = this.synPicGdtPost(url, params);
		ResponseBean resBean = JSON.parseObject(resultStr.toJSONString(), ResponseBean.class);
		//调用成功
		if (resBean != null && resBean.getCode() != null && "0".equals(resBean.getCode())) {
			Map<String, Object> data = resBean.getData();
			AdMaterialPlatform adp = new AdMaterialPlatform();
			// 1 广点通
			adp.setPlatformId(Integer.valueOf(PlatformTypeEnum.GDT.getValue()));
			adp.setMaterialId(adMaterial.getId());
			// 广告账户
			adp.setAdvertiserId(advertiserId);
			adp.setPlatformFileId(String.valueOf(data.get("image_id")));
			adp.setPlatformMaterialId(String.valueOf(data.get("image_id")));
			adp.setMd5(adMaterial.getMd5());
			adp.setCreateUser(loginUserId);
			adp.setCreateTime(new Date());
			return adp;
		} else {
			throw new CheckedException("图片同步广点通失败：" + resBean.getMessage());
		}
	}
	
	/**
	 *  广点通：推送图片
	 * @param url
	 * @param data
	 * @return
	 */
	private JSONObject synPicGdtPost(String url, Map<String, Object> data) {
		// 构造请求
		HttpPost httpPost = new HttpPost(url);
		// 文件参数
		FileBody file = new FileBody(new File(String.valueOf(data.get("realPath"))));
		MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addPart("file", file);
		// 其他参数
		entityBuilder.addTextBody("account_id", String.valueOf(data.get("account_id")));
		entityBuilder.addTextBody("upload_type", String.valueOf(data.get("upload_type")));
		entityBuilder.addTextBody("signature", String.valueOf(data.get("signature")), ContentType.APPLICATION_JSON);
		ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
		entityBuilder.addTextBody("description", String.valueOf(data.get("description")), contentType);
		HttpEntity entity = entityBuilder.build();
		CloseableHttpResponse response = null;
		CloseableHttpClient client = null;
		try {
			client = HttpClientBuilder.create().build();
			httpPost.setURI(URI.create(url));
			httpPost.setEntity(entity);
			response = client.execute(httpPost);
			if (response != null && response.getStatusLine().getStatusCode() == 200) {
				BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				StringBuilder result = new StringBuilder();
				String line = "";
				while ((line = bufferedReader.readLine()) != null) {
					result.append(line);
				}
				return JSONObject.parseObject(result.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new JSONObject();
	}
	
}
